<template>
    <div class="es_manage_span">
        <table-span
            :current-page="tabelData.current"
            :page-size="tabelData.size"
            :total="tabelData.total"
            :isShowTool="false"
            :isShowPagePlug="false">
            <template v-slot:searchItem>
                <div class="search_item_span">
                    <el-button icon="Search" size="default" type="primary" @click="searchData">查询</el-button>
                </div>
                <div class="search_item_span">
                    <el-button icon="Plus" size="default"
                        type="primary" :disabled="!(btOption.btCreateIndex)"
                        @click="createIndex">新增索引</el-button>
                </div>
                <div class="search_item_span">
                    <el-button icon="Setting" size="default"
                        type="primary" :disabled="!(btOption.btCustomOperate)"
                        @click="customOperate">自定义操作</el-button>
                </div>
            </template>
            <template v-slot:searchTable>
                <el-table :data="esList" size="default" height="100%" style="width: 100%;">
                    <el-table-column
                        align="center"
                        type="index"
                        width="50">
                    </el-table-column>
                    <el-table-column
                        align="center"
                        prop="index"
                        label="索引"
                        min-width="260">
                    </el-table-column>
                    <el-table-column
                        align="center"
                        prop="docs.count"
                        label="数据量"
                        width="120">
                    </el-table-column>
                    <el-table-column
                        align="center"
                        prop="docs.deleted"
                        label="删除数量"
                        width="120">
                    </el-table-column>
                    <el-table-column
                        align="center"
                        prop="store.size"
                        label="数据大小"
                        width="120">
                    </el-table-column>
                    <el-table-column
                        fixed="right"
                        align="center"
                        label="操作"
                        width="240">
                        <template #default="scope">
                            <el-button size="small" type="success" :disabled="!(btOption.btIndexMapping)"
                                @click="getIndexMapping(scope.$index, scope.row)">配置信息</el-button>
                            <el-button size="small" type="danger"  :disabled="!(btOption.btDeleteIndex)"
                                @click="deleteIndex(scope.$index, scope.row)" v-show="scope.row['docs.count'] <= 0">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </template>
        </table-span>
        <el-dialog
            title="索引mapping"
            v-model="indexMappingShow"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            @open="indexMappingOpen"
            @closed="indexMappingClosed"
            width="450px">
                <div id="jsoneditor" style="width: 410px;height: 500px;"></div>
        </el-dialog>
        <el-dialog
            title="新增索引"
            v-model="createIndexShow"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            @open="createIndexOpen"
            :before-close="createIndexBeforeClose"
            @closed="createIndexClosed"
            width="450px">
            <el-form ref="createIndexRef" :model="createIndexFrom" label-width="60px" :rules="createIndexRules">
                <el-form-item label="索引" prop="index">
                    <el-input v-model="createIndexFrom.index" />
                </el-form-item>
                <el-form-item label="配置">
                    <div id="createJsoneditor" style="width: 410px;height: 400px;"></div>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button size="default" @click="createIndexShow=false">取 消</el-button>
                <el-button size="default" type="primary" @click="saveIndex">保存</el-button>
            </template>
        </el-dialog>
        <el-dialog
            title="自定义操作"
            v-model="esCustomShow"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            @open="esCustomOpen"
            @closed="esCustomClosed"
            top="10vh"
            width="450px">
            <el-form ref="esCustomRef" :model="esCustomForm" label-width="60px" :rules="esCustomRules">
                <el-form-item label="方式" prop="method">
                    <el-select v-model="esCustomForm.method" placeholder="请选择请求方式" style="width: 410px">
                        <el-option
                        v-for="item in esMethod"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="地址" prop="endpoint">
                    <el-input v-model="esCustomForm.endpoint" />
                </el-form-item>
                <el-form-item label="类型">
                    <el-select
                        v-model="esCustomForm.type"
                        placeholder="请选择参数类型"
                        style="width: 410px"
                    >
                    <el-option
                        v-for="item in paramTypeList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                        />
                </el-select>
                </el-form-item>
                <el-form-item label="参数">
                    <div id="customJsoneditor" style="width: 410px;height: 200px;"></div>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="customRequest">发送请求</el-button>
                </el-form-item>
                <el-form-item label="结果">
                    <div id="showCustomJsoneditor" style="width: 410px;height: 220px;"></div>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>
<script>
    import TableSpan from '@/components/table-span.vue';
    import {tool} from "@/js/tool.js";
    import { ElMessage } from 'element-plus'
    import JSONEditor from 'jsoneditor';

    export default {
        name: "elasticsearch",
        data: function(){
            return {
                btOption: {
                    btCreateIndex: null,
                    btCustomOperate: null,
                    btIndexMapping: null,
                    btDeleteIndex: null
                },
                tabelData: {
                    total: 0,
                    size: 10,
                    current: 1,
                    records: []
                },
                esList: null,
                searchCondition: {
                    index: ""
                },
                indexMappingShow: false,
                indexMappingData: null,
                jsoneditor: null,

                createIndexShow: false,
                createJsoneditor: null,
                createIndexFrom: {
                    index: null,
                    config: null
                },
                createIndexRules: {
                    index: [
                        { required: true, message: '请填写索引信息', trigger: 'blur' }
                    ]
                },
                esCustomShow: false,
                esCustomForm: {
                    method: null,
                    endpoint: null,
                    type: 1, //1、parameters;2、jsonEntity
                    parameters: null,
                    jsonEntity: null
                },
                paramTypeList: [
                    {value: 1, label: '字符串参数'},
                    {value: 2, label: 'JSON参数'},
                ],
                esCustomRules: {
                    method: [
                        { required: true, message: '请选择请求方式', trigger: 'blur' }
                    ],
                    endpoint: [
                        { required: true, message: '请填写请求地址', trigger: 'blur' }
                    ]
                },
                esMethod: [
                    {value: "GET", label: "GET"},
                    {value: "POST", label: "POST"},
                    {value: "PUT", label: "PUT"},
                    {value: "DELETE", label: "DELETE"},
                    {value: "HEAD", label: "HEAD"}
                ],
                customEditor: null,
                showCustomEditor: null
            }
        },
        methods: {
            searchData: function(){
                getAllIndexList(this);
            },
            createIndex: function(){
                this.createIndexShow = true;
            },
            createIndexOpen: function(){
                const container = document.getElementById("createJsoneditor");
                const options = {
                    mode: 'text', //code存在问题，删除时会间隔删除！！！
                    mainMenuBar: true
                };
                this.createJsoneditor = new JSONEditor(container, options);
                const jsonInit = {
                    aliases: {},
                    mappings: {
                        properties: {}
                    },
                    settings: {
                        index: {
                            number_of_shards: 1,
                            number_of_replicas: 0
                        }
                    }
                }
                this.createJsoneditor.set(jsonInit);
            },
            createIndexBeforeClose: function(){
                var obj = this;
                this.$confirm("是否放弃创建索引").then(function(){
                    obj.createIndexShow = false;
                }).catch(function(){});
            },
            createIndexClosed: function(){
                this.createIndexFrom={
                    index: null,
                    config: null
                }
                this.createJsoneditor.destroy();
            },
            saveIndex: function(){
                const obj = this;
                this.$refs["createIndexRef"].validate(function (valid) {
                    if (valid) {
                        saveIndex(obj);
                    }
                });
            },
            customOperate: function(){
                this.esCustomShow = true;
            },
            getIndexMapping: function(index, row){
                getIndexMapping(this, row);
                this.indexMappingShow = true;
            },
            indexMappingOpen: function(){
                const container = document.getElementById("jsoneditor");
                const options = {
                    mode: 'preview',
                    mainMenuBar: false
                };
                this.jsoneditor = new JSONEditor(container, options);
                const aceEditor = this.jsoneditor['aceEditor'];
                // aceEditor.setReadOnly(true);
            },
            indexMappingClosed: function(){
                this.jsoneditor.destroy();
            },
            esCustomOpen: function(){
                const container = document.getElementById("customJsoneditor");
                const options = {
                    mode: 'text',
                    mainMenuBar: false
                };
                this.customEditor = new JSONEditor(container, options);

                const showContainer = document.getElementById("showCustomJsoneditor");
                const showOptions = {
                    mode: 'code',
                    mainMenuBar: false
                };
                this.showCustomEditor = new JSONEditor(showContainer, showOptions);
                const aceEditor = this.showCustomEditor['aceEditor'];
                aceEditor.setReadOnly(true);
            },
            esCustomClosed: function(){
                this.customEditor.destroy();
                this.showCustomEditor.destroy();
            },
            customRequest: function(){
                const obj = this;
                this.$refs["esCustomRef"].validate(function (valid) {
                    if (valid) {
                        if(obj.esCustomForm.type == 1){
                            obj.esCustomForm.parameters = obj.customEditor.get();
                            obj.esCustomForm.jsonEntity = null;
                        }else{
                            obj.esCustomForm.parameters = null;
                            obj.esCustomForm.jsonEntity = JSON.stringify(obj.customEditor.get());
                        }
                        obj.showCustomEditor.setText("");
                        customRequest(obj);
                    }
                });
            },
            deleteIndex: function(index, row){
                var obj = this;
                this.$confirm("是否要删除索引：" + row.index).then(function(){
                    deleteIndex(obj, row);
                }).catch(function(){});
            }
        },
        created: function(){
            const menuId = [this.$route.query.menuId]
            const obj = this;
            new tool.getAuthorisedRequest(menuId, this.btOption, function(){
                getAllIndexList(obj);
            });
        },
        components: {
            TableSpan
        }
    }

    /**
     * 获取所有的索引信息
     */
    function getAllIndexList(app){
        const param = {}
        const url = "/basic/elasticsearch/index/list";
        tool.formJsonRequest(url,param,null,function(data){
            if(data.code === "0000"){
                app.esList = data.data;
            }else{
                ElMessage({
                    showClose: true,
                    message: data.message,
                    type: 'error'
                });
            }
        });
    }

    /**
     * 获取索引的配置信息
     */
     function getIndexMapping(app, row){
        const param = {
            index: row.index
        }
        const url = "/basic/elasticsearch/index";
        tool.formJsonRequest(url,param,null,function(data){
            if(data.code === "0000"){
                app.indexMappingData = data.data;
                app.jsoneditor.set(app.indexMappingData);
            }else{
                ElMessage({
                    showClose: true,
                    message: data.message,
                    type: 'error'
                });
            }
        });
    }

    /**
     * 保存索引信息
     */
    function saveIndex(app){
        const param = {
            index: app.createIndexFrom.index,
            config: JSON.stringify(app.createJsoneditor.get())
        }
        const url = "/basic/elasticsearch/createIndex";
        tool.formJsonRequest(url,param,null,function(data){
            if(data.code === "0000"){
                app.createIndexShow = false;
                getAllIndexList(app);
            }else{
                ElMessage({
                    showClose: true,
                    message: data.message,
                    type: 'error'
                });
            }
        });
    }

    /**
     * 删除索引信息
     */
    function deleteIndex(app, row){
        const param = {
            index: row.index
        }
        const url = "/basic/elasticsearch/deleteIndex";
        tool.formJsonRequest(url,param,null,function(data){
            if(data.code === "0000"){
                getAllIndexList(app);
            }else{
                ElMessage({
                    showClose: true,
                    message: data.message,
                    type: 'error'
                });
            }
        });
    }

    /**
     * ES自定义信息请求
     */
     function customRequest(app){
        const param = app.esCustomForm;
        const url = "/basic/elasticsearch/customOperate";
        tool.formJsonRequest(url,param,null,function(data){
            if(data.code === "0000"){
                try {
                    app.showCustomEditor.set(JSON.parse(data.data));
                } catch (error) {
                    //无法解析成json
                    app.showCustomEditor.setText(data.data);
                }
            }else{
                ElMessage({
                    showClose: true,
                    message: data.message,
                    type: 'error'
                });
            }
        });
    }
</script>
<style>
.es_manage_span{
    position: relative;
    display: flex;
    flex-direction: row;
    width: 100%;
    height: 100%;
    font-family: Microsoft YaHei,Heiti SC,tahoma,arial,Hiragino Sans GB,"\5B8B\4F53",sans-serif;
}
.search_item_span{
    max-width: 190px;
    height: auto;
    margin-top: 5px;
    margin-left: 10px;
}
.es_manage_span .search_item_fix_width{
    width: 370px;
    height: auto;
    margin-top: 5px;
    margin-left: 10px;
}
.es_manage_span .search_item_input_width{
    width: 200px;
    height: auto;
    margin-top: 5px;
    margin-left: 10px;
}
</style>